﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.UI;
using DevExpress.Web;
using DevExpress.Web.Data;
using TheHeGeo.Util;
using TheHeGeoDao;

namespace TheHeGeo.UserControl
{
    public partial class UcEquipmentManagerEnglish : System.Web.UI.UserControl
    {
        protected void Page_Init(object sender, EventArgs e)
        {
            LoadGrvData();

        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Session[SessionConst.SES_EQ_MANAGEMENT_GRVDATA] = null;
                LoadGrvData();
            }
            else
            {
                grvData.DataSource = Session[SessionConst.SES_EQ_MANAGEMENT_GRVDATA];
            }
        }

        protected void LoadGrvData()
        {
            LoadDaColumnItems();

            int dt = 1;
            string cu = ((SessionUser) Session[SessionConst.SES_USER]).NguoiSuDung.UserName;
            var list = (from o in DaoHelper.Entities.PhanQuyenDuAns
                join d in DaoHelper.Entities.DuAns on o.MaDuAn equals d.MaDuAn
                join t in DaoHelper.Entities.ThietBis on o.MaDuAn equals t.MaDuAn
                where (o.UserName.Equals(cu))
                select new
                {
                    t.MaThietBi,
                    t.MoTa,
                    t.TenThietBi,
                    TgLayMau = (double)t.TgLayMau / (double)dt,
                    TgLuuTheNho = (double)t.TgLuuTheNho / (double)dt,
                    t.TgGuiData,
                    t.BufferSize,
                    d.TenDuAn,
                    d.MaDuAn,
                    t.Status,
                    t.LastUpdate,
                    t.Id
                });
            var data = new DataTable();
            data.Columns.Add("MaThietBi", typeof(string));
            data.Columns.Add("MoTa", typeof(string));
            data.Columns.Add("TenThietBi", typeof(string));
            data.Columns.Add("TgLayMau", typeof(double));
            data.Columns.Add("TgLuuTheNho", typeof(double));
            data.Columns.Add("TgLtn", typeof(string));
            data.Columns.Add("TenDuAn", typeof(int));
            data.Columns.Add("TgLmDv", typeof(string));
            data.Columns.Add("Mk", typeof(string));
            data.Columns.Add("DisplayStatus", typeof(string));
            data.Columns.Add("Status", typeof(int));
            data.Columns.Add("Id", typeof(int));
            data.Columns.Add("TgGuiData", typeof(int));
            data.Columns.Add("BufferSize", typeof(int));

            data.Columns.Add("TgLmPcg", typeof(int));
            data.Columns.Add("TgLtnPcg", typeof(int));
            foreach (var l in list)
            {
                DataRow dr = data.NewRow();
                dr["MoTa"] = l.MoTa;
                dr["MaThietBi"] = l.MaThietBi;
                dr["TenThietBi"] = l.TenThietBi;
                dr["TgLayMau"] = (int)l.TgLayMau;
                dr["TgLuuTheNho"] = (int)l.TgLuuTheNho;
                dr["TgLtn"] = "1";
                dr["TgLmDv"] = "1";
                dr["TenDuAn"] = l.MaDuAn;
                if (l.Status == Common.EquipmentStop)
                    dr["DisplayStatus"] = "Stop using";
                else if (l.Status == Common.EquipmentMoved)
                    dr["DisplayStatus"] = "Moved to other project";
                else if (l.LastUpdate == null)
                {
                    dr["DisplayStatus"] = "There is no update time";
                }
                else
                    dr["DisplayStatus"] = l.Status == Common.EquipmentRunning ? ("Update time:" + l.LastUpdate.Value.ToString("yyyy/MM/dd HH:mm:ss.ff")) : ("");

                dr["Status"] = l.Status;
                dr["Id"] = l.Id;
                dr["TgLmPcg"] = (l.TgLayMau - (int) l.TgLayMau)*10;
                dr["TgLtnPcg"] = 0;
                dr["TgGuiData"] = l.TgGuiData ?? 1;
                dr["BufferSize"] = l.BufferSize ?? 1;
                data.Rows.Add(dr);
            }

            Session[SessionConst.SES_EQ_MANAGEMENT_GRVDATA] = data;
            // grvData.KeyFieldName = "MaThietBi";

            grvData.DataSource = data;
            grvData.DataBind();
        }

        protected void cbbTimeType_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadGrvData();
        }

        protected void grvData_RowUpdating(object sender, ASPxDataUpdatingEventArgs e)
        {
            ChangeGrvReadOnly(true);
            int maDa = Convert.ToInt32(e.NewValues["TenDuAn"]);
            int oldMaDa = Convert.ToInt32(e.OldValues["TenDuAn"]);
            var str = (string) e.OldValues["MaThietBi"];
            ThietBi tb = DaoHelper.Entities.ThietBis.FirstOrDefault(p => p.MaThietBi == str && p.Status == Common.EquipmentRunning);
            if (tb != null)
            {
                if (tb.MaDuAn != oldMaDa)
                    throw new ArgumentException(
                        "Equipment has been moved to another project, You can not change equipment's information in this project");
            }
            if (!ValidateDuAn(maDa))
                throw new ArgumentException("The choiced project is paused or finished, please choice another project");
            if (CanEdit(maDa))
            {
                var tgianlaymau = Convert.ToDouble(e.NewValues["TgLayMau"]) * (Convert.ToInt32(e.NewValues["TgLmDv"])) + (Convert.ToDouble(e.NewValues["TgLmPcg"] ?? e.OldValues["TgLmPcg"]) / 10);
                if (tgianlaymau > Convert.ToDouble(e.NewValues["TgGuiData"]))
                    throw new Exception("sample timing must be less than sending interval!.");
                try
                {
                    int tgltn = Convert.ToInt32(e.NewValues["TgLtn"]);
                    int tglm = Convert.ToInt32(e.NewValues["TgLmDv"]);
                    TheheGeoDbEntities enti = DaoHelper.ReOpen();
                    if (e.OldValues["TenDuAn"].ToString() != e.NewValues["TenDuAn"].ToString())
                    {
                        ThietBi oldThietbi =DaoHelper.Entities.ThietBis.FirstOrDefault(p => p.MaDuAn == oldMaDa && p.MaThietBi == str);
                        if (oldThietbi != null)
                            oldThietbi.Status = Common.EquipmentMoved;
                        List<ThietBi> enl =
                            (from s in enti.ThietBis where (s.MaThietBi == str && s.MaDuAn == maDa) select s).ToList();
                        if (enl.Count > 0)
                        {
                            ThietBi ent = enl[0];
                            ent.TenThietBi = (string) e.NewValues["TenThietBi"];
                            ent.MoTa = (string) e.NewValues["MoTa"];
                            ent.TgLayMau = Convert.ToDouble(e.NewValues["TgLayMau"]) * tglm + (Convert.ToDouble(e.NewValues["TgLmPcg"] ?? e.OldValues["TgLmPcg"]) / 10);
                            ent.TgLuuTheNho = Convert.ToDouble(e.NewValues["TgLuuTheNho"])*tgltn; /*+ (Convert.ToDouble(e.NewValues["TgLtnPcg"] ?? e.OldValues["TgLtnPcg"]) / 10);*/
                            ent.NeedUpdate = true;
                            ent.TgGuiData = Convert.ToInt32(e.NewValues["TgGuiData"]);
                            ent.BufferSize = Convert.ToInt32(e.NewValues["BufferSize"]);
                            ent.Status = Common.EquipmentRunning;
                        }
                        else
                        {
                            var ent = new ThietBi();
                            ent.MaThietBi = str;
                            ent.MaDuAn = maDa;
                            ent.TenThietBi = (string) e.NewValues["TenThietBi"];
                            ent.MoTa = (string) e.NewValues["MoTa"];
                            ent.TgLayMau = Convert.ToDouble(e.NewValues["TgLayMau"]) * tglm + (Convert.ToDouble(e.NewValues["TgLmPcg"]??e.OldValues["TgLmPcg"])/10);
                            ent.TgLuuTheNho = Convert.ToDouble(e.NewValues["TgLuuTheNho"])*tgltn;/* + (Convert.ToDouble(e.NewValues["TgLtnPcg"] ?? e.OldValues["TgLtnPcg"]) / 10);*/
                            ent.NeedUpdate = true;
                            ent.TgGuiData = Convert.ToInt32(e.NewValues["TgGuiData"]);
                            ent.BufferSize = Convert.ToInt32(e.NewValues["BufferSize"]);
                            ent.Status = Common.EquipmentRunning;
                            DaoHelper.Entities.ThietBis.Add(ent);
                        }
                    }
                    else
                    {
                        UpdateThietBi(e);
                    }
                    DaoHelper.Entities.SaveChanges();
                }
                catch (Exception)
                {
                    throw new Exception("Cập nhật không thành công. Vui lòng thử lại.");
                }
            }
            else
            {
                throw new ArgumentException("Bạn không có quyền điều chỉnh thông tin");
            }
            e.Cancel = true;
            grvData.CancelEdit();
            LoadGrvData();
        }

        protected void UpdateThietBi(ASPxDataUpdatingEventArgs e)
        {
            int maDa = Convert.ToInt32(e.NewValues["TenDuAn"]);
            var str = (string) e.OldValues["MaThietBi"];
            int tgltn = Convert.ToInt32(e.NewValues["TgLtn"]);
            int tglm = Convert.ToInt32(e.NewValues["TgLmDv"]);
            TheheGeoDbEntities enti = DaoHelper.ReOpen();
            List<ThietBi> enl =
                (from s in enti.ThietBis where (s.MaThietBi == str && s.MaDuAn == maDa) select s).ToList();
            ThietBi ent = enl[0];
            ent.TenThietBi = (string) e.NewValues["TenThietBi"];
            ent.MoTa = (string) e.NewValues["MoTa"];
            ent.TgLayMau = Convert.ToDouble(e.NewValues["TgLayMau"]) * tglm + (Convert.ToDouble(e.NewValues["TgLmPcg"] ?? e.OldValues["TgLmPcg"]) / 10);
            ent.TgLuuTheNho = Convert.ToDouble(e.NewValues["TgLuuTheNho"])*tgltn;/* + (Convert.ToDouble(e.NewValues["TgLtnPcg"] ?? e.OldValues["TgLtnPcg"]) / 10);*/
            ent.Status = Common.EquipmentRunning;
            ent.TgGuiData = Convert.ToInt32(e.NewValues["TgGuiData"]);
            ent.BufferSize = Convert.ToInt32(e.NewValues["BufferSize"]);
            ent.NeedUpdate = true;
        }

        protected void grvData_RowValidating(object sender, ASPxDataValidationEventArgs e)
        {
            if (e.Errors.Count > 0)
                e.RowError = "Please input again!";
        }

        private void AddError(Dictionary<GridViewColumn, string> errors, GridViewColumn column, string errorText)
        {
            if (errors.ContainsKey(column)) return;
            errors[column] = errorText;
        }

        protected void grvData_StartRowEditing(object sender, ASPxStartRowEditingEventArgs e)
        {
            ChangeGrvReadOnly(false);

            var f = grvData.Columns["MaThietBi"] as GridViewDataColumn;
            if (f != null)
            {
                f.ReadOnly = true;
            }
        }
        protected void DeleteSensorData(string maTB, int maDA)
        {
            try
            {
                var lSensor = (from s in DaoHelper.Entities.Sensors
                               join e in DaoHelper.Entities.ThietBis on s.MaThietBi equals e.MaThietBi
                               join p in DaoHelper.Entities.DuAns on e.MaDuAn equals p.MaDuAn
                               where (e.MaThietBi == maTB && p.MaDuAn == maDA)
                               select new
                               {
                                   s.MaSensor,
                                   p.MaDuAn
                               }).ToList();
                if (lSensor != null && lSensor.Count > 0)
                {
                    foreach (var s in lSensor)
                    {
                        var vSensorTest = (from v in DaoHelper.Entities.SensorValuesTests
                                           where (v.MaDuAn == s.MaDuAn && v.MaSensor == s.MaSensor)
                                           select v).ToList();
                        DaoHelper.Entities.SensorValuesTests.RemoveRange(vSensorTest);
                        var vSensor1000 = (from v in DaoHelper.Entities.SensorValues1000
                                           where (v.MaDuAn == s.MaDuAn && v.MaSensor == s.MaSensor)
                                           select v).ToList();
                        DaoHelper.Entities.SensorValues1000.RemoveRange(vSensor1000);
                        var vSensorLatest = (from v in DaoHelper.Entities.SensorLatestValues
                                             where (v.MaDuAn == s.MaDuAn && v.MaSensor == s.MaSensor)
                                             select v).ToList();
                        DaoHelper.Entities.SensorLatestValues.RemoveRange(vSensorLatest);
                        //DaoHelper.Entities.SaveChanges();
                        //return 1;
                    }
                }

            }
            catch (Exception)
            {

                //return -1;
            }

        }

        protected void DeleteSensorByMaTb(string maTb)
        {
            try
            {
                var lSensor = (from s in DaoHelper.Entities.Sensors where s.MaThietBi == maTb select s).ToList();
                if (lSensor != null && lSensor.Count > 0)
                    DaoHelper.Entities.Sensors.RemoveRange(lSensor);
            }
            catch (Exception)
            {


            }

        }
        protected void grvData_RowDeleting(object sender, ASPxDataDeletingEventArgs e)
        {
            string mtb = e.Values["MaThietBi"].ToString();
            int maDa = Convert.ToInt32(e.Values["TenDuAn"]);
            if (CanEdit(maDa))
            {
                try
                {
                   // DeleteSensorData(mtb, maDa);
                   // DeleteSensorByMaTb(mtb);
                    ThietBi rs =
                        DaoHelper.Entities.ThietBis.FirstOrDefault(p => p.MaThietBi == (mtb) && p.MaDuAn == maDa);
                    if (rs != null)
                    {
                        DaoHelper.Entities.ThietBis.Remove(rs);
                    }

//                    var ls = DaoHelper.Entities.Sensors.Where(p => p.MaThietBi==(mtb)).ToList();
//                    DaoHelper.Entities.Sensors.RemoveRange(ls);

                    DaoHelper.Entities.SaveChanges();
                }
                catch (Exception)
                {
                    throw new Exception("Delete unsuccessfull");
                }
            }
            else
            {
                throw new ArgumentException("You have not permission editing");
            }
            e.Cancel = true;
            grvData.CancelEdit();
            LoadGrvData();
        }

        protected void Msg()
        {
            ScriptManager.RegisterStartupScript(Page, GetType(), "alert2",
                "<script type='text/javascript'>alert('You have not permission editing')</script>", false);
        }

        protected void grvData_RowInserting(object sender, ASPxDataInsertingEventArgs e)
        {
            ChangeGrvReadOnly(true);
            string mtb = e.NewValues["MaThietBi"].ToString();
            int maDa = Convert.ToInt32(e.NewValues["TenDuAn"]);
            if (CanEdit(maDa))
            {
                try
                {
                    if (!ValidateDuAn(maDa))
                        throw new ArgumentException("The choiced project is paused or finished, please choice another project");
                    ThietBi oldThietbi = DaoHelper.Entities.ThietBis.FirstOrDefault(p => p.MaThietBi == mtb && p.Status == 0);
                    if (oldThietbi != null)
                        throw new ArgumentException("Equipment ID is existing, please input another ID");
                    grvData.Columns["Mk"].Visible = false;
                    string nsd = ((SessionUser) Session[SessionConst.SES_USER]).NguoiSuDung.UserName;

                    var ttb = (string) e.NewValues["TenThietBi"];
                    var mk = (string) e.NewValues["Mk"];
                    var mota = (string) e.NewValues["MoTa"];
                    double tgltn = Convert.ToDouble(e.NewValues["TgLuuTheNho"])*Convert.ToInt32(e.NewValues["TgLtn"]);/* + (Convert.ToDouble(e.NewValues["TgLtnPcg"] ) / 10);*/
                    double tglm = Convert.ToDouble(e.NewValues["TgLayMau"]) * Convert.ToInt32(e.NewValues["TgLmDv"]) + (Convert.ToDouble(e.NewValues["TgLmPcg"]) / 10);
                    Int32 tgguidata = Convert.ToInt32(e.NewValues["TgGuiData"]);
                    Int32 buffersize = Convert.ToInt32(e.NewValues["BufferSize"]);
                    if (!UserHelper.CheckFollowPwdEncrypt(mtb, mk))
                    {
                        throw new ArgumentException("PassWord or Equipment ID is not correct!");
                    }

                    var s = new ThietBi();
                    s.MaThietBi = mtb;
                    s.MoTa = mota;
                    s.TenThietBi = ttb;
                    s.TgLayMau = tglm;
                    s.TgLuuTheNho = tgltn;
                    s.NeedUpdate = true;
                    s.MaDuAn = maDa;
                    s.TgGuiData = tgguidata;
                    s.BufferSize = buffersize;
                    s.Status = Common.EquipmentRunning;
                    DaoHelper.Entities.ThietBis.Add(s);

                    DaoHelper.Entities.SaveChanges();
                }
                catch (ArgumentException)
                {
                    throw;
                }
                catch (Exception)
                {
                    throw new Exception("Add successfull");
                }
            }
            else
            {
                throw new ArgumentException("You have not permission editing!");
            }
            e.Cancel = true;
            grvData.CancelEdit();

            LoadGrvData();
        }

        protected bool CanEdit(int maDa)
        {
            string user = ((SessionUser) (Session[SessionConst.SES_USER])).NguoiSuDung.UserName;
            List<PhanQuyenDuAn> tb = (from q in DaoHelper.Entities.PhanQuyenDuAns
                where (q.UserName.Equals(user) && q.MaDuAn.Equals(maDa) && q.Role.Equals(Common.R_W_D))
                select q).ToList();
            if (tb.Count > 0)
                return true;
            return false;
        }

        protected void LoadDaColumnItems()
        {
            var cbb = grvData.Columns["TenDuAn"] as GridViewDataComboBoxColumn;
            if (cbb == null) return;
            string user = ((SessionUser) (Session[SessionConst.SES_USER])).NguoiSuDung.UserName;
            cbb.PropertiesComboBox.Items.Clear();
            cbb.PropertiesComboBox.ValueType = typeof (int);
            List<DuAn> dt = (from d in DaoHelper.Entities.PhanQuyenDuAns
                join e in DaoHelper.Entities.DuAns on d.MaDuAn equals e.MaDuAn
                             where (d.UserName.Equals(user) )
                select e).ToList();
            foreach (DuAn phanQuyenDuAn in dt)
            {
                cbb.PropertiesComboBox.Items.Add(phanQuyenDuAn.TenDuAn, phanQuyenDuAn.MaDuAn);
            }
        }

        protected bool ValidateEqId(string id, string pass)
        {
            return true;
        }
        protected bool ValidateDuAn(int maDA)
        {
            var da = (from p in DaoHelper.Entities.DuAns
                      where p.MaDuAn == maDA
                      select p).FirstOrDefault();
            if (da.Status == Common.ProjectRunning)
                return true;
            return false;

        }
        protected void ChangeGrvReadOnly(bool readOnly)
        {
            var c = grvData.Columns["TgLtn"] as GridViewDataColumn;
            if (c != null)
            {
                c.ReadOnly = readOnly;
            }

            var d = grvData.Columns["TgLmDv"] as GridViewDataColumn;
            if (d != null)
            {
                d.ReadOnly = readOnly;
            }

            var f = grvData.Columns["MaThietBi"] as GridViewDataColumn;
            if (f != null)
            {
                f.ReadOnly = readOnly;
            }

            var g = grvData.Columns["TgLtnPcg"] as GridViewDataComboBoxColumn;
            if (g != null)
            {
                g.ReadOnly = readOnly;
            }

            var h = grvData.Columns["TgLmPcg"] as GridViewDataComboBoxColumn;
            if (h != null)
            {
                h.ReadOnly = readOnly;
            }
        }

        protected void grvData_InitNewRow(object sender, ASPxDataInitNewRowEventArgs e)
        {
            ChangeGrvReadOnly(false);

            e.NewValues["TgLuuTheNho"] = 1;
            e.NewValues["TgLayMau"] = 1;
            e.NewValues["TgLtn"] = "1";
            e.NewValues["TgLmDv"] = "1";
            e.NewValues["TgLtnPcg"] = "0";
            e.NewValues["TgLmPcg"] = "0";
            grvData.Columns["Mk"].Visible = true;
        }

        protected void grvData_ParseValue(object sender, ASPxParseValueEventArgs e)
        {
            if (e.FieldName.Equals("MaThietBi"))
            {
                if (e.Value == null || string.IsNullOrEmpty(e.Value.ToString()))
                {
                    throw new Exception("Please input Equipment ID");
                }
            }
            if (e.FieldName.Equals("Mk"))
            {
                if (e.Value == null || string.IsNullOrEmpty(e.Value.ToString()) && grvData.Columns["Mk"].Visible)
                {
                    throw new Exception("Please input password");
                }
            }
            if (e.FieldName.Equals("TenDuAn"))
            {
                if (e.Value == null || string.IsNullOrEmpty(e.Value.ToString()))
                {
                    throw new Exception("Please choice project!");
                }
            }
        }
        protected void StartSensor(int rowIndex)
        {
            var idTb = Convert.ToInt32(grvData.GetRowValues(rowIndex, "Id"));

            var TB = (from e in DaoHelper.Entities.ThietBis
                      where (e.Id == idTb)
                      select e).FirstOrDefault();
            if (TB != null && TB.Status != Common.EquipmentMoved)
            {
                TB.Status = Common.EquipmentRunning;
                DaoHelper.Entities.SaveChanges();
            }


        }

        protected void StopSensor(int rowIndex)
        {
            var idTb = Convert.ToInt32(grvData.GetRowValues(rowIndex, "Id"));

            var TB = (from e in DaoHelper.Entities.ThietBis
                      where (e.Id == idTb)
                      select e).FirstOrDefault();
            if (TB != null && TB.Status != Common.EquipmentMoved)
            {
                TB.Status = Common.EquipmentStop;
                DaoHelper.Entities.SaveChanges();
            }
        }
        protected void grvData_CustomButtonCallback(object sender, ASPxGridViewCustomButtonCallbackEventArgs e)
        {
            switch (e.ButtonID)
            {
                case "grvBtnStart":
                    StartSensor(e.VisibleIndex);
                    break;

                case "grvBtnStop":
                    StopSensor(e.VisibleIndex);
                    break;

            }
            LoadGrvData();
        }

        protected void grvData_CustomButtonInitialize(object sender, ASPxGridViewCustomButtonEventArgs e)
        {
            e.Enabled = true;
            var tt = grvData.GetRowValues(e.VisibleIndex, "Status") as Int32?;
            if (!tt.HasValue || tt == Common.EquipmentRunning)
            {
                if (e.ButtonID.Equals("grvBtnStart"))
                {
                    e.Enabled = false;
                    e.Image.Url = "~/Master/images/startBtnDisable.png";
                }
            }
            if (tt == Common.EquipmentStop)
            {
                if (e.ButtonID.Equals("grvBtnStop"))
                {
                    e.Enabled = false;
                    e.Image.Url = "~/Master/images/stopBtnDisable.png";
                }
            }
            else if (tt == Common.EquipmentMoved)
            {
                if (e.ButtonID.Equals("grvBtnStop"))
                {
                    e.Enabled = false;
                    e.Image.Url = "~/Master/images/stopBtnDisable.png";
                }
                if (e.ButtonID.Equals("grvBtnStart"))
                {
                    e.Enabled = false;
                    e.Image.Url = "~/Master/images/startBtnDisable.png";
                }
            }
        }
    }
}